1 Load the packages

suppressPackageStartupMessages({
library(knitr)
library(pander)
library(dygraphs)
library(zoo)
library(Quandl)
library(ggplot2)
})

2 R Markdown Layout

3 Global settings

Before writing your RMarkdown document, user can specify the global settings for the global environment. For example, setting whether to echo your R code and show the code/results etc. in the document. You can either set the options globally or for individual code blocks.

## global setting for all blocks

{r setup, include = FALSE}
knitr::opts_chunk$set(echo = TRUE)

## setting for individual code block

{r chuck_name, echo = FALSE, results = "hide", include = TRUE}
x <- rnorm(100)
y <- 2*x + rnorm(100)

If you want all the figures take the same amount of space, use the following commands:

{r global_options, include = FALSE}
knitr::opts_chunk$set(fig.width = 12, fig.height = 8, fig.path = 'Figs/',
                      echo = FALSE, warning = FALSE, message = FALSE)
# While setting figure path, the '/' is very import.                      

Also, you can individually change the settings for your figure windows. This will overwrite global settings. This is very convenient especially when you have images for different data size. For example, by specifying ‘fig.with’ and ‘fig.height’:

{r scatterplot, fig.width = 8, fig.height = 6}
plot(x,y)

4 Create Paragraphs With Styles

4.1 Headers

# Header 1
## Header 2
### Header 3

4.2 Lists

4.2.1 Unordered List

* Item 1
* Item 2
    + Item 2a
    + Item 2b

This is the example output for Unordered Lists:

  • Item 1
  • ITem 2
    • Item 2a
    • Item 2b

4.2.2 Ordered List

1. Item 1
2. Item 2
3. Item 3
    + Item 3a
    + Item 3b

This is the example output for ordered list:

  1. Item 1
  2. Item 2
  3. Item 3
    • Item 3a
    • Item 3b

4.3 Emphasis

From time to time, we might want to emphasize our text either using {**bold**} or {*italic*}. Also, we can change the text color by using styles. We can say roses are red, violets are blue by using command <span style="color:red">red</span> and <span style="color:blue">blue</span> repsectively.

5 Embed code chunk, inline code and run R code

5.1 R Code Chunks

R code will be evaluated and printed

size = 750
x = as.data.frame(matrix(runif(14*size),ncol=14))
head(x)
##          V1         V2        V3        V4        V5         V6         V7
## 1 0.2826153 0.27619028 0.2147521 0.1365030 0.6038595 0.65325169 0.03552247
## 2 0.7671862 0.86837233 0.3679879 0.9271022 0.8745636 0.86130532 0.22411733
## 3 0.6158803 0.04620431 0.1696513 0.1200033 0.1273721 0.49674987 0.88338218
## 4 0.3449832 0.84746335 0.0284731 0.9341338 0.5529134 0.02383497 0.86995211
## 5 0.8399923 0.33462644 0.4105045 0.5085341 0.4479008 0.89362047 0.20574309
## 6 0.1708209 0.73196337 0.1178317 0.9711985 0.5453431 0.52892483 0.83249019
##          V8        V9        V10          V11        V12       V13
## 1 0.8295534 0.6976623 0.04591954 0.7829101176 0.97276066 0.6032213
## 2 0.4352041 0.4899945 0.59168662 0.5728689663 0.35471090 0.9498747
## 3 0.9384053 0.9173653 0.49125009 0.1842383607 0.34319323 0.7180012
## 4 0.7877587 0.2565447 0.26821289 0.4111792219 0.04415267 0.4957210
## 5 0.7301219 0.6665794 0.70052458 0.0004130306 0.35711218 0.9748445
## 6 0.6704121 0.6650134 0.16385878 0.0552149068 0.83045260 0.2445284
##           V14
## 1 0.467044100
## 2 0.792592079
## 3 0.657415150
## 4 0.351200123
## 5 0.006000512
## 6 0.640000520

5.2 Embed Code Chunk

In RMarkdown, we can symply embed a chunk of code by using

x = matrix(runif(14*size),ncol=14)
y = 10 * sin(pi*x[,1]*x[,2]) + 20*(x[,3]-0.5)**2 + 10*x[,4] + 5*x[,5] + runif(1,0,1)
x[,11:14] = x[,1:4] + matrix(runif(4*size,min = 0, max = 0.025),ncol=4)

5.3 Inline Code

Inline code can be excecuted using two plus two equals 4 using two plus two equals 4

6 Generate R Graphics and Table

data=data.frame(value=rnorm(10000))
# Basic histogram
ggplot(data, aes(x=value)) + geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

# Custom Binning. I can just give the size of the bin
ggplot(data, aes(x=value)) + geom_histogram(binwidth = 0.05)

# Uniform color
ggplot(data, aes(x=value)) + 
    geom_histogram(binwidth = 0.2, color="white", fill=rgb(0.2,0.7,0.1,0.4) ) 

# Proportional color
ggplot(data, aes(x=value)) + 
    geom_histogram(binwidth = 0.2, aes(fill = ..count..) )

8 Embed Mathematic Equations

There are two ways to embed equations using LaTex format: inline equation and block equations.

8.1 Inline Equation

This is an example of inline equation using $ quotes. $10sin(\pi x_1x_2)$ ==> \(10sin(\pi x_1x_2)\)

8.2 Display Equations

This is an example of display equations using $$ quotes. $$y = 10sin(\pi x_1x_2) + 20(x_3-0.5)^2 + 10x_4+5x_5+\epsilon$$=> \[y = 10sin(\pi x_1x_2) + 20(x_3-0.5)^2 + 10x_4+5x_5+\epsilon\]

9 Tables

R Markdown can also create simple tables very easily by following syntax:

First Header | Second Header
------------ | -------------
Content Cell | Content Cell
Content Cell | Content Cell
Content Cell | Content Cell
Reference Style Links and Images

Here is an example output:

Name Age Hobby
Jack 22 Travel
Adam 33 Movie
Judy 25 Party

10 Auto Cite References

In RMarkdown, we can also easily cite our references by coupling with reference managers. For example: Application written in the R programming language (R Core Team 2016) using the Shiny framework (Tutorialspoint 2015).

11 Advanced Features

RMarkdown can also embed advanced objects into its HTML output: video, interactive graphics etc. Here are some examples of the advanced features:

11.1 Interactive graphs

11.1.1 Interactive time series

brent <- Quandl("EIA/PET_RBRTE_D", collapse="monthly", type="ts")
dygraph(brent, main = "Brent Spot Prices") %>% dyRangeSelector() %>% 
  dyAxis("y", label = "US $/Barrel") %>%
  dySeries("V1", label = "Brent ($/Barrel)") %>%
  dyLegend(show = "follow")

11.1.2 GeoSpatial Visualization

library(leaflet)
m <- leaflet() %>%
  addTiles() %>%  # Add default OpenStreetMap map tiles
  addMarkers(lng=-77.003, lat=38.9, popup="IHS MARKIT")
m  # Print the map

11.1.3 rbokeh

library(rbokeh)
figure() %>%
  ly_points(Sepal.Length, Sepal.Width, data = iris,
    color = Species, glyph = Species,
    hover = list(Sepal.Length, Sepal.Width))

11.1.4 networkViz

library(visNetwork)
nodes <- data.frame(id = 1:6, title = paste("node", 1:6), 
                    shape = c("dot", "square"),
                    size = 10:15, color = c("blue", "red"))
edges <- data.frame(from = 1:5, to = c(5, 4, 6, 3, 3))
visNetwork(nodes, edges) %>%
  visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE)

11.1.5 plotly

library(ggplot2)
library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
p <- ggplot(data = diamonds, aes(x = cut, fill = clarity)) +
            geom_bar(position = "dodge")
ggplotly(p)
## Warning: We recommend that you use the dev version of ggplot2 with `ggplotly()`
## Install it with: `devtools::install_github('hadley/ggplot2')`

11.1.6 networkD3

# Load data
library(networkD3)
## 
## Attaching package: 'networkD3'
## The following object is masked from 'package:leaflet':
## 
##     JS
data(MisLinks)
data(MisNodes)

# Plot
forceNetwork(Links = MisLinks, Nodes = MisNodes,
            Source = "source", Target = "target",
            Value = "value", NodeID = "name",
            Group = "group", opacity = 0.8)
URL <- paste0(
        "https://cdn.rawgit.com/christophergandrud/networkD3/",
        "master/JSONdata//flare.json")

## Convert to list format
Flare <- jsonlite::fromJSON(URL, simplifyDataFrame = FALSE)

# Use subset of data for more readable diagram
Flare$children = Flare$children[1:3]

radialNetwork(List = Flare, fontSize = 10, opacity = 0.9)
diagonalNetwork(List = Flare, fontSize = 10, opacity = 0.9)
hc <- hclust(dist(USArrests), "ave")

dendroNetwork(hc, height = 600)

11.2 Video

htmltools::includeHTML("embed_video_Rmarkdown.html")

REFERENCES

R Core Team. 2016. “R: A Language and Envirnoment for Statistical Computing.” Journal Article. http:///www.R-project.org.

Tutorialspoint. 2015. “Perl Programming.”